<template>
  <div>
    <div class="margin-container-list">
      <div class="clearfix border-b">
        <div class="pad-t-15 pad-b-20 font-17 fl">
          <el-button @click="addCommander" class="open-btn" type="primary">新建</el-button>
        </div>
      </div>
      <div class="top-operate-default mar-b-20">
        <div class="search-item">
          <label>搜索：</label>
          <el-select v-model="dataListQuery.keywordType" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-input v-model="dataListQuery.keyword" @keyup.enter.native="handleSearch" placeholder="请输入搜索内容"
            style="width: 300px"></el-input>
          <label class="mar-l-20">自提点类型：</label>
          <el-select v-model="dataListQuery.takeTypeId" placeholder class="pad-l-10 takeSelect" placeholder="请选择自提点类型">
            <el-option v-for="item in takeTypeList" v-if="item.takeTypeCategoryId != 2" :key="item.takeTypeId"
              :label="item.takeTypeName" :value="item.takeTypeId">
            </el-option>
          </el-select>
          <label class="mar-l-20">筛选时间：</label>
          <el-date-picker v-model="datePicker" type="daterange" unlink-panels range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
          <el-button-group>
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
            <el-button plain="" @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
          element-loading-text="加载中" style="width: 100%">
          <el-table-column width="55px" type="selection"></el-table-column>
          <el-table-column min-width="240px" label="团长信息" prop="userInfo">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <label>
                  <img :src="scope.row.avatar" class="user-avatar" v-if="scope.row.avatar">
                  <img v-else src="https://veekrayimg.joinsun.vip/head-portrait.png" class="user-avatar-r" alt="">
                </label>
                <div class="font-14 pad-l-10">
                  <div>昵称：<span v-if="scope.row.memberId > 0">{{scope.row.nickname}}</span><span v-else>--</span></div>
                  <div>手机：<span v-if="scope.row.memberId > 0">{{scope.row.phone}}</span><span v-else>--</span></div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="240px" width="370" label="提货点信息">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <el-image v-if="scope.row.takeAddressPicUrl" style="width: 100px; height: 70px"
                  :src="scope.row.takeAddressPicUrl" :preview-src-list="[scope.row.takeAddressPicUrl]">
                </el-image>
                <div class="font-12 pad-l-10">
                  <div>{{scope.row.takeName}}</div>
                  <div style="color: red;">{{scope.row.takeTypeName}}</div>
                  <div>
                    {{scope.row.provinceName}}{{scope.row.cityName}}{{scope.row.districtName}}{{scope.row.takeAddress}}
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="200px" label="累计成交">
            <template slot-scope="scope">
              <div>订单：<span v-if="scope.row.memberId > 0">{{scope.row.accumulativeDealNum}}</span><span v-else>--</span>
              </div>
              <div>金额：<span v-if="scope.row.memberId > 0">{{scope.row.accumulativeDealAmount}}</span><span
                  v-else>--</span></div>
            </template>
          </el-table-column>
<!--          <el-table-column width="120px" label="门店二维码" prop="storeWxCode">
            <template slot-scope="scope">
              <div v-if="scope.row.storeWxCode">
                <el-image style="width: 50px; height: 50px" :src="scope.row.storeWxCode"
                  :preview-src-list="[scope.row.storeWxCode]"></el-image>
              </div>
              <div v-else><span>--</span>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column width="240px" label="开通时间" prop="createTime">
            <template slot-scope="scope">
              <div><span v-if="scope.row.memberId > 0">{{scope.row.createTime}}</span><span v-else>--</span></div>
            </template>
          </el-table-column>
          <el-table-column min-width="240px" label="状态">
            <template slot-scope="scope">
              <div v-if="scope.row.commanderType == 1">启用</div>
              <div v-if="scope.row.commanderType == 0">禁用</div>
            </template>
          </el-table-column>
          <el-table-column width="140px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="bingUserMember(scope.row)"
                v-if="scope.row.memberId == null || scope.row.memberId == 0">绑定微客</el-button>
              <el-button type="text" size="medium" @click="handleUpdate(scope.row)">查看</el-button>
              <el-button type="text" size="medium" @click="enableDisable(scope.row, 1)"
                v-if="scope.row.memberId != null && scope.row.commanderType == 0">启用</el-button>
              <el-button type="text" size="medium" @click="enableDisable(scope.row, 0)"
                v-if="scope.row.memberId != null && scope.row.commanderType == 1">禁用</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <pagination v-show="total>0" :total="total" :page.sync="dataListQuery.currentPage"
        :limit.sync="dataListQuery.size" @pagination="initData" />
      <!-- 地理坐标 -->
      <el-dialog width="700px" v-el-drag-dialog title="请选择地点" :visible.sync="dialogMapVisible">
        <iframe id="mapPage" width="100%" height="600px" frameborder=0 :src="coord">
        </iframe>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogMapVisible = false">取消</el-button>
          <el-button type="primary" @click="onSetLocation(loc)">确定</el-button>
        </div>
      </el-dialog>

      <!-- 团长绑定微客弹窗 -->
      <el-dialog title="团长绑定码" class="code-area-box" :visible.sync="bingCommanderMemberCodeVisible" width="340px"
        :show-close="false" :close-on-click-modal="true">
        <div class="code-box">
          <img :src="bingCommanderMemberCode" v-if="bingCommanderMemberCode" />
        </div>
        <div slot="footer" class="dialog-footer">
          <p>用微信"扫一扫" 扫描上方二维码</p>
          <p>绑定提货点【{{bingTakeName}}】</p>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {
    pagingCommander,
    saveCommander,
    saveCommanderType,
    getCommanderBindCode
  } from '@/api/user/commander'
  import {
    getTakeLocationTypeList
  } from '@/api/system/takeLocationType'
  import elDragDialog from '@/directive/el-dragDialog'
  export default {
    directives: {
      // 拖动窗口
      elDragDialog
    },
    data() {
      return {
        options: [{
          value: 'nickname',
          label: '团长昵称'
        }, {
          value: 'nickphone',
          label: '团长手机号'
        }, {
          value: 'takename',
          label: '提货点名称'
        }, {
          value: 'takeaddress',
          label: '提货点地址'
        }],
        total: 0,
        dataList: [],
        listLoading: false,
        dialogMapVisible: false,
        dataListQuery: {
          keywordType: 'nickname',
          keyword: '',
          nickname: '',
          enterpriseId: this.getEnterpriseId(),
          startTime: '',
          endTime: '',
          currentPage: 1,
          size: 10,
          takeTypeId: ''
        },
        entity: {},
        datePicker: [],
        loc: null,
        coord: '',
        takeTypeList: [],
        statusFlag: {},
        bingCommanderMemberCode: undefined,
        bingTakeName: undefined,
        bingCommanderMemberCodeVisible: false
      }
    },
    // 初始化页面
    created() {
      window.addEventListener('message', function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        const loc = event.data
        if (loc && loc.module === 'locationPicker') {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          this.loc = {
            ...loc
          }
        }
      }, false)
      this.listLoading = false
      this.initData()
      // 自提点类型列表
      this.getTakeTypeList()
    },
    mounted() {},
    methods: {
      getTakeTypeList() {
        getTakeLocationTypeList().then(response => {
          this.takeTypeList = response
          this.takeTypeList.unshift({
            'takeTypeId': '',
            'takeTypeName': '全部'
          })
        })
      },
      handleClick() {
        this.initData()
      },
      onSetLocation() {
        if (window.loc && window.loc.latlng) {
          this.entity.lng = window.loc.latlng.lng
          this.entity.lat = window.loc.latlng.lat
          this.entity.takeAddress = window.loc.poiaddress
        }
        this.saveData()
      },
      dialogMapVisibleClick(row) {
        const obj = JSON.parse(JSON.stringify(row))
        this.entity = obj
        this.coord =
          'https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=web&coord=' +
          obj.lat + ',' + obj.lng
        this.dialogMapVisible = true
      },
      initData() {
        this.listLoading = true
        // const datePicker = this.datePicker
        if (this.datePicker && this.datePicker.length > 0) {
          this.dataListQuery.startDate = this.datePicker[0]
          this.dataListQuery.endDate = this.datePicker[1]
        } else {
          this.dataListQuery.startDate = ''
          this.dataListQuery.endDate = ''
        }
        this.dataListQuery.applySource = 1
        pagingCommander(this.dataListQuery).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.listLoading = false
          this.statusFlag = response.data.dict.statusFlag
        })
      },
      // 保存用户信息
      saveData() {
        if (!this.entity.lng) {
          this.$message.error('经度不能为空')
          return
        }
        if (!this.entity.lat) {
          this.$message.error('纬度不能为空')
          return
        }
        if (!this.entity.takeAddress) {
          this.$message.error('提货地址不能为空')
          return
        }
        saveCommander(this.entity).then((response) => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.dialogMapVisible = false
          this.initData()
        })
      },
      resetSearch() {
        this.dataListQuery = {
          nickname: '',
          enterpriseId: this.getEnterpriseId(),
          startTime: '',
          endTime: '',
          currentPage: 1,
          size: 10,
          keywordType: 'nickname',
          keyword: '',
          takeTypeId: ''
        }
        this.datePicker = []
        this.initData()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 查询
      handleSearch() {
        this.dataListQuery.currentPage = 1
        this.initData()
      },
      enableDisable(row, commanderType) {
        if (row.memberId) {
          saveCommanderType(row.commanderId, commanderType).then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: '保存成功!'
            })
            this.handleSearch()
          })
        } else {
          this.msgError('请先绑定微客信息,才能修改状态!')
        }
      },
      // 编辑
      handleUpdate(row) {
        this.$router.push({
          path: '/community/commander/EditCommander',
          query: {
            commanderId: row.commanderId
          }
        })
      },
      // 新增团长
      addCommander() {
        this.$router.push({
          path: '/community/commander/EditCommander',
          query: {
            commanderId: 0
          }
        })
      },
      // 绑定微客
      bingUserMember(row) {
        if (!row.memberId) {
          this.bingTakeName = row.takeName
          // this.bingCommanderMemberCode = 'https://veekrayimg.joinsun.vip/head-portrait.png'
          this.bingCommanderMemberCodeVisible = true
          getCommanderBindCode({
            commanderId: row.commanderId
          }).then(response => {
            this.bingCommanderMemberCode = response.data
          })
        } else {
          this.bingTakeName = undefined
          this.bingCommanderMemberCode = undefined
          this.msgError('该团长已绑定微客!')
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .mission-type {
    padding: 35px 38px;
    min-width: 150px;
    border: 1px solid #dcdcdc;
    border-radius: 8px;
    margin: 25px 40px;
    cursor: pointer;
    text-align: center;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  }

  .flex-cag-box {
    padding: 0px 0px 20px 70px;

    .mission-type:nth-child(4n) {
      margin-right: 0px;
    }
  }

  .next-step-btn {
    padding: 13px 35px;
    font-size: 18px;
  }

  .sel-mission-type {
    background-color: #409eff;
    color: #fff;
  }

  .budget-el-select {
    padding-top: 10px;
    padding-left: 50px;
  }

  .user-avatar {
    width: 46px;
    height: 46px;
    display: block;
    border-radius: 50px;
  }

  .takeSelect {
    /deep/.el-input {
      width: 220px;
    }
  }

  .code-box {
    width: 90%;
    margin: 0 auto;
    text-align: center;
    border-radius: 10px;
    background: #ffffff;
    padding: 30px;

    img {
      width: 90%;
    }
  }
</style>
